package org.tangzsoft.pdmviewer.utils.config;

public abstract class AbstractPropertySet implements PropertySet {

	protected abstract String getProperty(String name) throws Exception;
	
	public boolean getBoolean(String name, boolean defaultValue) {
		String stringValue = getString(name, "" + defaultValue);
        boolean value = new Boolean(stringValue).booleanValue();
        return value;
	}

	public Class<?> getClass(String name, Class<?> defaultValue) {
		String className = null;
        if ( defaultValue == null ) {
          className = getString(name, name);
        } else {
          className = getString(name, defaultValue.getName());
        }

        Class<?> retClass = null;
        
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
		if (cl == null) {
		    cl = ClassLoader.getSystemClassLoader();
		}
        
		try {
            //Using the thread's ContextClassLoader gives ClassCastEx in JUnit.
            //retClass = Thread.currentThread().getContextClassLoader().loadClass(className);
        	retClass = Class.forName(className, true, cl);
        } catch (ClassNotFoundException e) {
            //System.err.println("[Config] Class '" + className + "' couldn't be loaded - defaulted to '" + defaultValue + "'");
            retClass = defaultValue;
        }

        return retClass;
	}

	public int getInteger(String name, int defaultValue) {
		String stringValue = getString(name, "" + defaultValue);

        int value = 0;
        try {
            value = Integer.parseInt(stringValue);
        } catch (NumberFormatException e) {
            //System.err.println("[Config] NumberFormatException on value '" + name + "', defaulted to " + defaultValue);
            value = defaultValue;
        }

        return value;
	}

	public String getString(String name, String defaultValue) {
		String value = null;
        try {
            value = getProperty(name);
        } catch (Exception e) {
            value = defaultValue;
        }
        return value;
	}

}
